<template>
  <div>
    <div id="target">
      <iv-input
        v-model="inputComment"
        type="textarea"
        :rows="3"
        :placeholder="placeholders">
      </iv-input>
      <div style="text-align: right;margin-top: 10px">
        <iv-button @click="cancel" style="margin-right: 10px">取消</iv-button>
        <iv-button type="primary" round @click="commitComment">确定</iv-button>
      </div>
    </div>


    <List item-layout="vertical" size="small" :split="false">
      <ListItem v-for="item in commentList" :key="item.id">
        <ListItem>
          <li style="margin-left: 0px;" v-show="item !== '' || item.content !== null"
              @click="showCommentInput(comment,item)">
            <span style="color: #2d9aff">{{ item.nickname }} </span>：{{ item.content }}
            <a style="margin-left: 30px;">
              <Icon type="ios-chatbubbles-outline"/>
              回复
            </a>
          </li>
          <!-- <template slot="action"> -->
          <!-- <li>
              <Icon type="ios-calendar-outline"/>
              {{dateFilter(item.createTime)}}
          </li> -->
          <!-- <li>
             <span @click="showCommentInput(item,item)"><Icon type="ios-chatbubbles-outline"/> 回复</span>
           </li> -->
          <!-- </template> -->
        </ListItem>
        <div v-if="item.replyComments" class='commentSecond'>
          <Reply :replyComment="item.replyComments" :comment='item'
                 v-on:showCommentInput="showCommentInput"></Reply>
        </div>
      </ListItem>
    </List>

  </div>
</template>

<script>

import Reply from './Reply'

export default {
  components: {
    Reply,
  },
  name: 'Comment',
  props: {
    commentList: Array,
    postId: Number,
  },
  data() {
    return {
      //评论内容
      inputComment: '',
      //输入框默认内容
      placeholders: '写下你的评论',
      comment: {},
      returnCityIp: {},
      osAndBrowser: null,
    }
  },
  mounted() {
    this.getUserIP();
    this.osAndBrowser = this.getOSAndBrowser();
  },
  methods: {
    /**
     * 点击取消按钮
     */
    cancel() {
      this.inputComment = '';
      this.placeholders = '写下你的评论';
      this.fromId = null;
    },
    /**
     * 提交评论
     */
    async commitComment() {
      const redata = JSON.parse(sessionStorage.getItem('currentManager'))
      let nickname = ""
      let byManagerId = null;
      if (redata) {
        nickname = redata.name
        byManagerId = redata.id
        scrollTo(0, 0);
      } else {
        let cookieName = this.$cookie.get('tourist_id');
        if (cookieName) {
          nickname = cookieName;
        } else {
          let name = '游客' + this.createCode();
          nickname = name;
          this.$cookie.set('tourist_id', name, "1y");
        }
      }
      if (!this.inputComment) {
        this.$Message.warning({
          background: true,
          content: '评论信息不能为空！',
        });
      } else {
        this.comment = {
          nickname: nickname,
          content: this.inputComment,
          articleId: this.postId,
          byManagerId: byManagerId,
          pid: this.fromId,
          ip: this.returnCityIp.cip,
          address: this.returnCityIp.cname,
          browser: this.osAndBrowser
        };
        this.$http({
          url: this.$http.adornUrl('/comment/save'),
          method: 'post',
          data: this.$https.adornDatas(this.comment)
        }).then(({data}) => {
          if (data.status !== 0) {
            this.$Message.error(data.result.error)
            return
          } else {
            this.$Message.success('评论成功')
            //传递到父组件查询最新评论
            this.$emit('getCommentList', this.postId)
          }
        })
      }
      this.placeholders = '写下你的评论';
      this.inputComment = '';
    },
    //根据id查询该博客的评论信息
    async showCommentById(id) {
      const {data: result} = await this.$http.get("/comment/" + id)
      if (result.code === 200) {
        this.commentList = result.data
      } else {
        this.$Message.success(result.message)
      }
    },
    /**
     * 生成5位随机数
     */
    createCode() {
      let code = '';
      //设置长度，这里看需求，我这里设置了4
      const codeLength = 4;
      //设置随机字符
      let random = new Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9);
      //循环codeLength 我设置的4就是循环4次
      for (let i = 0; i < codeLength; i++) {
        //设置随机数范围,这设置为0 ~ 36
        let index = Math.floor(Math.random() * 9);
        //字符串拼接 将每次随机的字符 进行拼接
        code += random[index];
      }
      console.log(code, 677)
      return code
    },
    /**
     * 获取当前地址
     */
    getUserIP() {
      this.returnCityIp = returnCitySN;
    },
    /**
     * 点击评论按钮显示输入框
     * item: 当前大评论
     * reply: 当前回复的评论
     */

    showCommentInput(item, reply) {
      if (reply) {
        this.placeholders = "@" + reply.nickname + " "
      } else {
        this.inputComment = ''
      }
      //当点击了回复时，页面滚动到评论框的位置
      document.getElementById("target").scrollIntoView();
      this.fromId = reply.id
    },
    //格式化时间的方法
    dateFilter(input) {
      var d = new Date(input);
      var year = d.getFullYear();
      var month = d.getMonth() < 9 ? "0" + (d.getMonth() + 1) : "" + (d.getMonth() + 1);
      var day = d.getDate() < 10 ? "0" + d.getDate() : "" + d.getDate();
      var hour = d.getHours() < 10 ? "0" + d.getHours() : "" + d.getHours();
      var minutes = d.getMinutes() < 10 ? "0" + d.getMinutes() : "" + d.getMinutes();
      var seconds = d.getSeconds() < 10 ? "0" + d.getSeconds() : "" + d.getSeconds();
      return (year + "-" + month + "-" + day + " " + hour + ":" + minutes + ":" + seconds);
    },
    /**
     * 获取当前系统和浏览器版本
     * @returns {string}
     */
    getOSAndBrowser(){
      let os = navigator.platform;
      let userAgent = navigator.userAgent;
      let info = "";
      let tempArray = "";
      if (os.indexOf("Win") > -1) {
        if (userAgent.indexOf("Windows NT 5.0") > -1) {
          info += "Win2000"
        } else if (userAgent.indexOf("Windows NT 5.1") > -1) {
          info += "WinXP"
        } else if (userAgent.indexOf("Windows NT 5.2") > -1) {
          info += "Win2003"
        } else if (userAgent.indexOf("Windows NT 6.0") > -1) {
          info += "WindowsVista"
        } else if (userAgent.indexOf("Windows NT 6.1") > -1 || userAgent.indexOf("Windows 7") > -1) {
          info += "Win7"
        } else if (userAgent.indexOf("Windows NT 6.2") > -1 || userAgent.indexOf("Windows 8") > -1) {
          info += "Win8"
        } else if (userAgent.indexOf("Windows NT 6.3") > -1 || userAgent.indexOf("Windows 8.1") > -1) {
          info += "Win8.1"
        } else if (userAgent.indexOf("Windows NT 10.0") > -1 || userAgent.indexOf("Windows 10") > -1) {
          info += "Win10"
        } else {
          info += "Other"
        }
      } else if (os.indexOf("Mac") > -1) {
        info += "Mac"
      } else if (os.indexOf("X11") > -1) {
        info += "Unix"
      } else if (os.indexOf("Linux") > -1) {
        info += "Linux"
      } else {
        info += "Other"
      }
      info += "/";
      let isOpera = userAgent.indexOf("Opera") > -1;
      let isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera;
      let isEdge = userAgent.toLowerCase().indexOf("edge") > -1 && !isIE;
      let isIE11 = (userAgent.toLowerCase().indexOf("trident") > -1 && userAgent.indexOf("rv") > -1);
      if (/[Ff]irefox(\/\d+\.\d+)/.test(userAgent)) {
        tempArray = /([Ff]irefox)\/(\d+\.\d+)/.exec(userAgent);
        info += tempArray[1] + tempArray[2]
      } else if (isIE) {
        let version = "";
        let reIE = new RegExp("MSIE (\\d+\\.\\d+);");
        reIE.test(userAgent);
        let fIEVersion = parseFloat(RegExp["$1"]);
        if (fIEVersion === 7) {
          version = "IE7"
        } else if (fIEVersion === 8) {
          version = "IE8"
        } else if (fIEVersion === 9) {
          version = "IE9"
        } else if (fIEVersion === 10) {
          version = "IE10"
        } else {
          version = "0"
        }
        info += version
      } else if (isEdge) {
        info += "Edge"
      } else if (isIE11) {
        info += "IE11"
      } else if (/[Cc]hrome\/\d+/.test(userAgent)) {
        tempArray = /([Cc]hrome)\/(\d+)/.exec(userAgent);
        info += tempArray[1] + tempArray[2]
      } else if (/[Vv]ersion\/\d+\.\d+\.\d+(\.\d)* *[Ss]afari/.test(userAgent)) {
        tempArray = /[Vv]ersion\/(\d+\.\d+\.\d+)(\.\d)* *([Ss]afari)/.exec(userAgent);
        info += tempArray[3] + tempArray[1]
      } else if (/[Oo]pera.+[Vv]ersion\/\d+\.\d+/.test(userAgent)) {
        tempArray = /([Oo]pera).+[Vv]ersion\/(\d+)\.\d+/.exec(userAgent);
        info += tempArray[1] + tempArray[2]
      } else {
        info += "unknown"
      }
      return info
    },
  },
}

</script>

<style scoped>
.commentSecond {
  padding: 2px;
  /* background-color: #EAEAEC; */
  border-radius: 5px;
  margin: 2px 10px;
}

list, listitem {
  display: block;
}
</style>
